// pages/detail/etail.js
const app = getApp();
const get = require('../../utils/common.js')
var WxParse = require('../../wxParse/wxParse.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    scrollTop: 100,
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 800,
    buynum: 1,
    goods_name: '',
    goods_id: '',
    sid: '',
    sale_price: 0,
    goods_img: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    var that = this
    let sid = options.id
    let moRenId = options.moRenId
    let upopenid = options.upopenid
    let openid = wx.getStorageSync('openid')
    var shareopenid = wx.getStorageSync('shareopenid')
    let telNum = wx.getStorageSync('telNum')
    if (options.telNum && options.telNum !== 'undefined') {
      telNum = options.telNum
    }

    that.setData({
      openid,
      sid,
      moRenId,
      telNum,
      upopenid,
      shareopenid
    })
    that.getUserInfoStorage()
    if (sid) {
      that.formShare() //从分享进来
    } else {
      that.fromMoRen() //默认活动详情
    }
  },
  onshow() {

  },
  //默认的sid请求数据
  fromMoRen(res) {
    let that = this

    get.getData('/goods/goodsdetail', { id: that.data.moRenId }).then(res => {

      var article = res.data.data.detail
      WxParse.wxParse('article', 'html', article, that, 5)
      that.setData({
        detail: res.data.data.detail,
        goods_id: res.data.data.id,
        goods_img: res.data.data.goods_img,
        title_img: res.data.data.title_img,
        goods_name: res.data.data.goods_name,
        goods_desc: res.data.data.goods_desc,
        price: res.data.data.price,
        sale_price: res.data.data.sale_price,
        stock: res.data.data.stock,
        link_type: res.data.data.link_type,
      })
      console.log("moren", that.data)
      console.log("moren", that.data.detail)
    }).catch(err => {

    })
  },
  // 分享请求detail
  formShare(res) {

    let that = this
    var sid = that.data.sid
    var upopenid = that.data.openid //这里的upopenid是下单人自己的openid
    get.getData('/useractiveprofession/checkuser', { sid: sid, upopenid: upopenid }).then(res => {
      var article = res.data.data.detail
      WxParse.wxParse('article', 'html', article, that, 5)
      that.setData({
        detail: res.data.data.detail,
        goods_id: res.data.data.id,
        goods_img: res.data.data.goods_img,
        title_img: res.data.data.title_img,
        goods_name: res.data.data.goods_name,
        goods_desc: res.data.data.goods_desc,
        price: res.data.data.price,
        sale_price: res.data.data.sale_price,
        stock: res.data.data.stock,
        link_type: res.data.data.link_type
      })
    }).catch(err => {

    })
  },
  //取缓存openid & session_key
  getUserInfoStorage() {
    let that = this
    let openid = wx.getStorageSync('openid')
    let session_key = wx.getStorageSync('session_key')

    that.setData({
      openid: openid,
      session_key: session_key
    })

  },
  // 加入购物车弹窗
  setModalStatus: function (e) {
    console.log(e)
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step();
    this.setData({
      animationData: animation.export(),
    })
    if (e.currentTarget.dataset.status == 1) {
      this.setData({
        showModalStatus: true,
        isScroll: false,
      });
    }
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation
      })
      if (e.currentTarget.dataset.status == 0) {
        this.setData(
          {
            showModalStatus: false
          }
        );
      }
    }.bind(this), 200)
  },
  // 加减
  changeNum: function (e) {
    var that = this;
    console.log(e)
    if (e.currentTarget.dataset.alphaBeta == 0) {
      if (that.data.buynum <= 1) {
        buynum: 1
      } else {
        this.setData({
          buynum: that.data.buynum - 1
        })
        console.log(that.data.buynum)
      };
    } else {
      this.setData({
        buynum: that.data.buynum + 1
      })
      console.log(that.data.buynum)
    };
  },
  //进入收藏列表
  shouCang(res) {
    console.log(res)
    let that = this
    var telNum = that.data.telNum
    var noShow = 1
    wx.redirectTo({
      url: '/pages/list/list?telNum=' + telNum + '&from_detail=' + noShow,
    })
  },
  //获取手机号码
  getPhoneNumber(e) {

    let that = this
    let session_key = that.data.session_key
    let openid = that.data.openid
    let encryptedData = e.detail.encryptedData
    let iv = e.detail.iv

    get.getData('/useractiveprofession/gettelnumber', { session_key: session_key, openid: openid, encryptedData: encryptedData, iv: iv }).then(res => {

      if (res.data.code == 10008) {
        let telJson = res.data.data
        telJson = JSON.parse(res.data.data)
        let tel = telJson.phoneNumber
        wx.setStorage({
          key: 'telNum',
          data: tel
        });
        that.setData({ telNum: tel })
        that.toPay(tel)
      } else {
        wx.showToast({
          title: '请先授权',
          image: '/pages/images/fail.png',
          cancelColor: '#f00',
          confirmColor: '#0DD164',
          duration: 1000
        });
        // that.hideModel()
      }
    }).catch(err => {

    })
  },
  //确定
  queDing(e) {
    let openid = this.data.openid
    get.getData('/useractiveprofession/isgrant', { openid: openid }).then(res => {

      const isTel = res.data.data
      const tel = res.data.tel
      if (isTel === 1) {
        this.toPay(tel)
      } else if (isTel === 2) {

        wx.showToast({
          title: '请先授权手机号',
          image: '/pages/images/fail.png',
          cancelColor: '#f00',
          confirmColor: '#0DD164',
          duration: 1000
        });
      }
      this.hideModel()
    })
  },
  //下單
  toPay(telNum) {

    let that = this
    let user_id = that.data.openid 
    let goods_id = that.data.goods_id
    let num = that.data.buynum
    let upopenid = that.data.upopenid || ''
    var shareopenid = that.data.shareopenid
    // let appid= app.d.appid
    get.getData('/order/order', { user_id: user_id, goods_id: goods_id, num: num, tel: telNum, upopenid: upopenid || shareopenid }).then(res => {

      if (res.data.code == 200) {
        var tip = res.data.msg
        wx.showToast({
          title: tip,
          image: '/pages/images/success.png',
          cancelColor: '#f00',
          mask: false,
          confirmColor: '#0DD164',
          duration: 1000
        });
        that.hideModel()
      } else if (res.data.code == 204) {
        var tip = res.data.msg
        wx.showToast({
          title: tip,
          image: '/pages/images/fail.png',
          cancelColor: '#f00',
          mask: false,
          confirmColor: '#0DD164',
          duration: 1000
        });
        that.hideModel()
      } else {
        var tip = res.data.msg
        wx.showToast({
          title: tip,
          image: '/pages/images/fail.png',
          cancelColor: '#f00',
          mask: false,
          confirmColor: '#0DD164',
          duration: 1000
        });
        that.hideModel()
      }
    }).catch(err => {
      var tip = err.data.msg
      wx.showToast({
        title: tip,
        image: '/pages/images/fail.png',
        cancelColor: '#f00',
        confirmColor: '#0DD164',
      });
    })

  },
  //隱藏彈窗
  hideModel() {
    let that = this

    var animation = wx.createAnimation({
      duration: 300,
      timingFunction: "linear",
      delay: 0
    })
    that.animation = animation
    animation.translateY(300).step()
    that.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      that.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(that), 200)

  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (options) {
    let that = this
    var sid = that.data.goods_id
    var openid = that.data.openid
    //  var sid = that.data.sid
    var title_img = that.data.title_img
    var goods_name = that.data.goods_name

    var shareObj = {
      title: goods_name,
      path: "/pages/login/login?sid=" + sid + '&openid=' + openid + '&shareopenid=' + that.data.shareopenid,
      imageUrl: title_img,
    }
    return shareObj
  },
  //回到顶部
  toTop: function (e) {
    console.log(e) // 一键回到顶部
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },
  //回到收藏
  toShoucang(e) {
    console.log(e) // 
    wx.redirectTo({
      url: '/pages/list/list',
    })
  }
})